<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :data-callback="dataCallback"
      :init-param="initParam"
      :request-api="getTableList"
      @drag-sort="sortTable"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button :icon="CirclePlus" type="primary" @click="openDrawer('新增工单', {}, 'Created')">添加工单 </el-button>
        <div class="mountBox">
          本月业绩:<span style="margin-left: 3px; font-weight: 600; color: #ac1717">{{
            proTable?.resData?.achievement?.currentMonth?.netAmount
          }}</span>
          <span style="margin-left: 20px">
            上月业绩:<span style="margin-left: 3px; font-weight: 600; color: #ac1717">{{
              proTable?.resData?.achievement?.previousMonth?.netAmount
            }}</span>
          </span>
        </div>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button link type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button :icon="View" link type="primary" @click="openDrawer('查看工单', scope.row)">查看 </el-button>
        <el-button
          v-if="
            (scope.row.status == 'Created' || scope.row.status == 'PendingReceipt' || scope.row.status == 'InTransit') &&
            scope.row.status !== 'CancellationPending'
          "
          :icon="Edit"
          link
          type="primary"
          @click="openDrawer('编辑工单', scope.row)"
        >
          编辑
        </el-button>
        <el-button
          v-if="
            scope.row.status !== 'PendingReceipt' &&
            scope.row.status !== 'InTransit' &&
            scope.row.status !== 'Completed' &&
            scope.row.status !== 'Abnormal' &&
            scope.row.status !== 'CancellationPending'
          "
          :icon="EditPen"
          link
          type="primary"
          @click="openDrawer('添加收货单号', scope.row, 'PendingReceipt')"
          >添加收货单号
        </el-button>
        <el-button
          v-if="
            scope.row.status == 'PendingReceipt' ||
            (scope.row.status !== 'PendingReceipt' &&
              scope.row.status !== 'InTransit' &&
              scope.row.status !== 'Created' &&
              scope.row.status !== 'Completed' &&
              scope.row.status !== 'Abnormal' &&
              scope.row.status !== 'CancellationPending')
          "
          :icon="EditPen"
          link
          type="primary"
          @click="openDrawer('添加寄出单号', scope.row, 'InTransit')"
          >添加寄出单号
        </el-button>
        <el-button
          v-if="
            scope.row.status !== 'PendingReceipt' &&
            scope.row.status !== 'Completed' &&
            scope.row.status !== 'Abnormal' &&
            scope.row.status !== 'Created' &&
            scope.row.status !== 'CancellationPending' &&
            (scope.row.repaymentAmount == '' || scope.row.repaymentAmount == undefined || scope.row.repaymentAmount == null)
          "
          :icon="EditPen"
          link
          type="primary"
          @click="openDrawer('添加回款金额', scope.row, 'unCompleted')"
          >添加回款金额{{ scope.row.repaymentAmount }}
        </el-button>
        <el-button
          v-if="
            scope.row.status !== 'Completed' &&
            scope.row.status !== 'Abnormal' &&
            scope.row.status !== 'PendingReceipt' &&
            scope.row.status !== 'InTransit' &&
            scope.row.status !== 'Created' &&
            userType !== 'Agent'
          "
          :icon="Reading"
          link
          @click="shenheCancel(scope.row)"
          >审核工单
        </el-button>
        <el-button
          v-if="scope.row.status !== 'Completed' && scope.row.status !== 'CancellationPending' && scope.row.status !== 'Abnormal'"
          :icon="CircleClose"
          link
          type="warning"
          @click="cancelAccount(scope.row)"
          >取消
        </el-button>
        <el-button v-if="userType !== 'Agent'" :icon="Delete" link type="warning" @click="deleteAccount(scope.row)"
          >删除
        </el-button>
      </template>
    </ProTable>
    <ListDrawer ref="ListDrawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script lang="tsx" name="useProTable" setup>
import { ref, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { User } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ListDrawer from "./listDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import {
  CirclePlus,
  Delete,
  EditPen,
  Edit,
  Reading,
  Download,
  Upload,
  View,
  Refresh,
  CircleClose
} from "@element-plus/icons-vue";
import { getUserList, deleteUser, editUser, addUser, resetUserPassword } from "@/api/modules/user";
import {
  getTicketMyList,
  addTicket,
  editTicket,
  customerWaitingCollected,
  wayToRecovery,
  cancelTicket,
  deleteTicket,
  auditTicket
} from "@/api/modules/list";
import { format, subMonths } from "date-fns";
import { useUserStore } from "@/stores/modules/user";
import { statusType } from "@/utils/dict";
const router = useRouter();
const userStore = useUserStore();
const userType = computed(() => userStore.userInfo.user_type);
// 跳转详情页
const toDetail = () => {
  router.push(`/proTable/useProTable/detail/${Math.random().toFixed(3)}?params=detail-page`);
};

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  console.log(data, "datadata");
  return {
    list: data.list,
    total: data.total
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  newParams.signingDateStart = newParams.signingDate ? newParams.signingDate[0] : undefined;
  newParams.signingDateEnd = newParams.signingDate ? newParams.signingDate[1] : undefined;
  newParams.sourceDateStart = newParams.sourceDate ? newParams.sourceDate[0] : undefined;
  newParams.sourceDateEnd = newParams.sourceDate ? newParams.sourceDate[1] : undefined;
  newParams.processingDateStart = newParams.processingDate ? newParams.processingDate[0] : undefined;
  newParams.processingDateEnd = newParams.processingDate ? newParams.processingDate[1] : undefined;
  delete newParams.signingDate;
  delete newParams.sourceDate;
  delete newParams.processingDate;
  return getTicketMyList(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

// 自定义渲染表头（使用tsx语法）
const headerRender = (scope: HeaderRenderScope<User.ResUserList>) => {
  return (
    <el-button type="primary" onClick={() => ElMessage.success("我是通过 tsx 语法渲染的表头")}>
      {scope.column.label}
    </el-button>
  );
};

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  // { type: "sort", label: "Sort", width: 80 },
  {
    prop: "code",
    width: 230,
    label: "入库编号",
    search: {
      el: "input",
      order: 1,
      span: 1
    }
  },
  {
    prop: "sourceDate",
    label: "来源日期",
    // headerRender,
    width: 210,
    render: scope => {
      return <>{format(scope.row.sourceDate, "yyyy-MM-dd ")}</>;
    },
    search: {
      el: "date-picker",
      span: 1,
      order: 5,
      props: { type: "daterange", valueFormat: "YYYY-MM-DD" }
      // defaultValue: [format(subMonths(new Date(), 1), "yyyy-MM-dd"), format(new Date(), "yyyy-MM-dd")]
    }
  },
  {
    prop: "processingDate",
    label: "来办日期",
    // headerRender,
    width: 180,
    render: scope => {
      return <>{format(scope.row.processingDate, "yyyy-MM-dd ")}</>;
    },
    search: {
      el: "date-picker",
      span: 1,
      order: 6,
      props: { type: "daterange", valueFormat: "YYYY-MM-DD" }
      // defaultValue: [format(subMonths(new Date(), 1), "yyyy-MM-dd"), format(new Date(), "yyyy-MM-dd ")]
    }
  },
  {
    prop: "source",
    label: "来源"
    // search: { el: "input", tooltip: "我是搜索提示" },
    // render: scope => {
    //   return (
    //     <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
    //       {scope.row.username}
    //     </el-button>
    //   );
    // }
  },
  {
    prop: "enterpriseId",
    label: "企业号",
    width: 130
    // search: { el: "input", tooltip: "我是搜索提示" },
    // render: scope => {
    //   return (
    //     <el-button type="primary" link onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}>
    //       {scope.row.username}
    //     </el-button>
    //   );
    // }
  },
  {
    prop: "customerName",
    width: 180,
    label: "客户名称",
    order: "1",
    search: {
      el: "input",
      span: 1,
      order: 2
    }
  },
  {
    prop: "customerAge",
    width: 180,
    label: "客户年龄"
  },
  {
    prop: "sesameScore",
    width: 180,
    label: "客户芝麻分"
  },
  {
    prop: "platform",
    label: "平台"
  },
  {
    prop: "deviceNumber",
    label: "第几台",
    width: 130
  },
  {
    prop: "modelColor",
    width: 180,
    label: "型号颜色"
  },
  {
    prop: "advanceAmount",
    width: 180,
    label: "垫付金额"
  },

  {
    prop: "customerReceiptTracking",
    width: 180,
    label: "收货快递单号",
    search: {
      el: "input",
      span: 1,
      order: 3
    }
  },
  {
    prop: "customerSendTracking",
    width: 180,
    label: "寄出快递单号",
    search: {
      el: "input",
      span: 1,
      order: 4
    }
  },
  {
    prop: "shippingFee",
    width: 100,
    label: "快递费"
  },
  {
    prop: "totalRepayment",
    width: 180,
    label: "共回款金额"
  },
  {
    prop: "merchantRecoveryAmount",
    width: 180,
    label: "商家回收金额"
  },
  {
    prop: "status",
    width: 180,
    label: "状态",
    // enum: statusType,
    fixed: "right",
    sortable: true,
    render: scope => {
      const matchedStatus = statusType.find(item => item.value === scope.row.status);
      return (
        <span class="statusBox" style={{ color: matchedStatus?.color || "#333", "--status-color": matchedStatus?.color }}>
          {matchedStatus?.label}
        </span>
      );
    }
  },
  {
    prop: "signingDate",
    width: 180,
    label: "签收日期",
    render: scope => {
      return <>{scope.row.signingDate ? format(scope.row.signingDate, "yyyy-MM-dd ") : "--"}</>;
    },
    search: {
      el: "date-picker",
      span: 1,
      props: { type: "daterange", valueFormat: "YYYY-MM-DD" }
      // defaultValue: [format(subMonths(new Date(), 1), "yyyy-MM-dd"), format(new Date(), "yyyy-MM-dd ")]
    }
  },

  { prop: "operation", label: "操作", fixed: "right", width: 620 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  ElMessage.success("修改列表排序成功");
};
// 取消
const cancelAccount = async (params: User.ResUserList) => {
  await useHandleData(cancelTicket, { id: params.id }, `取消工单【${params.code}】,待管理员审核`);
  proTable.value?.getTableList();
}; // 取消
const deleteAccount = async (params: User.ResUserList) => {
  await useHandleData(deleteTicket, { id: params.id }, `删除工单【${params.code}】`);
  proTable.value?.getTableList();
};
// 审核取消
const shenheCancel = async (params: User.ResUserList) => {
  ElMessageBox.confirm(`是否通过${params.createdBy}的工单${params.code}取消申请?`, "温馨提示", {
    confirmButtonText: "通过",
    cancelButtonText: "不通过",
    draggable: true
  })
    .then(async () => {
      await auditTicket({ id: params.id, audit: "Approved" })
        .then(res => {
          ElMessage({
            type: "success",
            message: `审核成功!`
          });
        })
        .finally(() => {
          proTable.value?.getTableList();
        });
    })
    .catch(async () => {
      await auditTicket({ ...params, audit: "Rejected" })
        .then(res => {
          ElMessage({
            type: "success",
            message: `审核成功!`
          });
        })
        .finally(() => {
          proTable.value?.getTableList();
        });
    });
};

// 批量删除用户信息
const batchDelete = async (id: string[]) => {
  await useHandleData(deleteUser, { id }, "删除所选用户信息");
  proTable.value?.clearSelection();
  proTable.value?.getTableList();
};

// 重置用户密码
const resetPass = async (params: User.ResUserList) => {
  await useHandleData(resetUserPassword, { id: params.id }, `重置【${params.username}】用户密码`);
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const ListDrawerRef = ref<InstanceType<typeof ListDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<User.ResUserList> = {}, status?: string) => {
  const params = {
    title,
    isView: title === "查看工单",
    row: { ...row },
    status: status,
    api:
      title === "新增工单"
        ? addTicket
        : title === "编辑工单" || title === "添加回款金额"
          ? editTicket
          : title === "添加收货单号"
            ? customerWaitingCollected
            : title === "添加寄出单号"
              ? wayToRecovery
              : undefined,
    getTableList: proTable.value?.getTableList
  };
  ListDrawerRef.value?.acceptParams(params);
};
</script>
<style lang="scss">
.statusBox {
  display: inline-block;
  width: 110px;
  height: 30px;
  font-weight: 500;
  line-height: 30px;
  &::before {
    display: inline-block;
    width: 6px;
    height: 6px;
    margin: 0 5px 2px 0;
    content: "";
    background-color: var(--status-color); // 使用 CSS 变量 margin-right: 5px; margin-bottom: 2px; }
    border-radius: 6px;
  }
}
.mountBox {
  height: 40px;
  font-size: 18px;
  line-height: 40px;
}
</style>
